Throwing general exceptions such as Exception
, SystemException
and ApplicationException
will have a negative
impact on any code trying to catch these exceptions.
From a consumer perspective, it is generally a best practice to only catch exceptions you intend to handle. Other exceptions should ideally be let
to propagate up the stack trace so that they can be dealt with appropriately. When a general exception is thrown, it forces consumers to catch
exceptions they do not intend to handle, which they then have to re-throw.
Besides, when working with a general type of exception, the only way to distinguish between multiple exceptions is to check their message, which is
error-prone and difficult to maintain. Legitimate exceptions may be unintentionally silenced and errors may be hidden.
For instance, if an exception such as StackOverflowException
is caught and not re-thrown, it may prevent the program from terminating
gracefully.
When throwing an exception, it is therefore recommended to throw the most specific exception possible so that it can be handled intentionally by
consumers.
Additionally, some reserved exceptions should not be thrown manually. Exceptions such as IndexOutOfRangeException
,
NullReferenceException
, OutOfMemoryException
or ExecutionEngineException
will be thrown automatically by the
runtime when the corresponding error occurs. Many of them indicate serious errors, which the application may not be able to recover from. It is
therefore recommended to avoid throwing them as well as using them as base classes.